package ms.unicorn.dsl.analysis.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import ms.unicorn.Element;
import ms.unicorn.dsl.analysis.AnalysisRegistryService;
import ms.unicorn.dsl.analysis.IAnalysis;

public class AnalysisRegistryServiceImpl implements AnalysisRegistryService {

	private List<IAnalysis> registry = new ArrayList<IAnalysis>();
	private List<AnalysisRegistryService.AnalysisRegistryListener> listeners = new ArrayList<AnalysisRegistryListener>();
	
	@Override
	public IAnalysis getAnalysis(Class<?> analysisType, Element element) {
		for (IAnalysis analysis: registry)
			if (analysisType.isInstance(analysis) && analysis.getRootElement().equals(element))
				return analysis;
		return null;
	}

	@Override
	public void registerAnalysis(IAnalysis analysis) {
		if (!registry.contains(analysis)) {
			registry.add(analysis);
			notify(AnalysisRegistryListener.ANALYSIS_REGISTERED, analysis);
		}
	}

	@Override
	public void unregisterAnalysis(IAnalysis analysis) {
		if (registry.remove(analysis))
			notify(AnalysisRegistryListener.ANALYSIS_UNREGISTERED, analysis);
	}

	@Override
	public void clearAll() {
		registry.clear();
		notify(AnalysisRegistryListener.ANALYSIS_CLEAR, null);
	}

	@Override
	public Collection<IAnalysis> getAnalyses(Class<?> analysisType) {
		List<IAnalysis> result = new ArrayList<IAnalysis>();
		for (IAnalysis analysis: registry)
			if (analysisType.isInstance(analysis))
				result.add(analysis);
		return result;
	}

	@Override
	public Collection<IAnalysis> getAnalyses(Element element) {
		List<IAnalysis> result = new ArrayList<IAnalysis>();
		for (IAnalysis analysis: registry)
			if (analysis.getRootElement().equals(element))
				result.add(analysis);
		return result;
	}
	
	public void notify(int what, IAnalysis changed) {
		for (AnalysisRegistryListener listener: listeners)
			listener.analysisChanged(what, changed);
	}

	@Override
	public void registerListener(AnalysisRegistryListener listener) {
		if (!listeners.contains(listener))
			listeners.add(listener);
	}

	@Override
	public void unregisterListener(AnalysisRegistryListener listener) {
		listeners.remove(listener);
	}

}
